import { ref, reactive, onMounted } from "vue";
import { Login } from '@/service/getInfo';
import router from '@/router/index';

interface User {
    username: string;
    password: string;
}

export const loginData = () => {
    const hover = ref<boolean>(false);
    const rememberMe = ref<boolean>(false); // 复选框状态
    const UserList = reactive<User>({
        username: '',
        password: '',
    });

    const logData = () => {
        console.log("用户名:", UserList.username);
        console.log("密码:", UserList.password);
    };

    // 页面加载时检查本地存储
    onMounted(() => {
        const savedUsername = localStorage.getItem("username");
        const savedPassword = localStorage.getItem("password");
        if (savedUsername && savedPassword) {
            UserList.username = savedUsername;
            UserList.password = savedPassword;
            rememberMe.value = true; // 自动勾选
        }
    });

    const isLogin = async (): Promise<void> => {
        try {
            const res = await Login(UserList);
            if (res && res.code === 200) {
                alert('登录成功');
                // 记住密码逻辑
                if (rememberMe.value) {
                    localStorage.setItem("username", UserList.username);
                    localStorage.setItem("password", UserList.password);
                } else {
                    localStorage.removeItem("username");
                    localStorage.removeItem("password");
                }
                // 登录成功后跳转
                router.push('/check');
            } else {
                alert('登录失败，请检查工号和密码');
            }
        } catch (error) {
            console.error("登录请求失败:", error);
            alert('登录出错，请稍后重试');
        }
    };

    return { UserList, isLogin, hover, rememberMe,logData };
};
